package com.example.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 定义 logger
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model model) {
        // 记录错误日志
        logger.error("An error occurred", e);
        // 将错误信息传递到前端
        model.addAttribute("errorMessage", "An error occurred. Please try again later.");
        return "error-page";
    }

    @ExceptionHandler(AnimeServiceException.class)
    public String handleAnimeServiceException(AnimeServiceException e, Model model) {
        // 记录错误日志
        logger.error("Anime service error", e);
        // 将错误信息传递到前端
        model.addAttribute("errorMessage", e.getMessage());
        return "error-page";
    }
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleNoResourceFoundException(NoResourceFoundException ex, Model model) {
        model.addAttribute("errorMessage", "Resource not found: " + ex.getResourcePath());
        return "error-page"; // 返回视图名称
    }
}
